package com.newlink.building.common_base.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent


/**
 * @Author: Jake
 * @Date: 2023-07-03
 * @Description:
 */
object Base_CommonUtils {
    
    fun isServiceRunning(context: Context, className: String): Boolean {
        var isRunning = false

        try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            // 获取运行中的服务列表，使用较大的数量以确保不遗漏
            val serviceList = activityManager.getRunningServices(Integer.MAX_VALUE)

            // 使用增强日志记录服务检查过程
            EnhancedLogger.service(
                tag = "CommonUtils",
                serviceName = "ServiceChecker",
                action = "CHECK_RUNNING_SERVICES",
                status = "Found ${serviceList.size} services"
            )

            for (info in serviceList) {
                EnhancedLogger.d("CommonUtils", "检查运行中的服务: ${info.service.className}")
                if (info.service.className == className) {
                    isRunning = true
                    EnhancedLogger.success("CommonUtils", "✓ 找到目标服务: $className")
                    break
                }
            }

            if (!isRunning) {
                EnhancedLogger.w("CommonUtils", "✗ 未找到目标服务: $className")
            }

        } catch (e: Exception) {
            EnhancedLogger.e(
                tag = "CommonUtils",
                message = "检查服务时发生异常: ${e.message}",
                throwable = e
            )
            // 发生异常时，假设服务未运行
            return false
        }

        return isRunning
    }

    fun printAllIntentExtras(intent: Intent?) {
        NLog.d(
            "|jake|..printAllIntentExtras intent=$intent"
        )
        if (intent == null) {
            NLog.d("|jake|..printAllIntentExtras intent is null")
            return
        }
        NLog.d("|jake|..printAllIntentExtras intent uri=" + intent.toUri(0))
    }

    fun getTopActivityName(context: Context): String? {
        try {
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val runningTaskInfo = activityManager.getRunningTasks(1)
            if (runningTaskInfo != null && runningTaskInfo.size > 0) {
                return runningTaskInfo[0].topActivity?.className
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun isActivityInStack(
        context: Context, activityClassName: String
    ): Boolean {
        val manager =
            context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        val runningTasks = manager.getRunningTasks(Int.Companion.MAX_VALUE)
        for (taskInfo in runningTasks) {
            if (taskInfo.topActivity?.className == activityClassName) {
                return true
            }
        }
        return false
    }

}